<template>
  <div class="add-active-container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <!-- 基础信息 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基础信息</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="form.activityName" placeholder="请输入活动名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动介绍" prop="activityIntroduce">
              <el-input v-model="form.activityIntroduce" placeholder="请输入活动介绍" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报名时间" prop="signTime">
              <el-date-picker
                v-model="form.signTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动时间" prop="activityTime">
              <el-date-picker
                v-model="form.activityTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否需要保证金">
              <el-radio-group v-model="form.ifBond">
                <el-radio :label="0">不需要</el-radio>
                <el-radio :label="1">需要</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保证金金额" v-if="form.ifBond === 1">
              <el-input-number v-model="form.bondMoney" :min="0" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="活动标签">
              <el-input v-model="form.activityLabel" placeholder="请输入活动标签" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="活动图片">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :http-request="handleAvatarSuccess"
              >
                <img v-if="form.image" :src="form.image" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 优惠规则 -->
      <el-card class="form-card" style="margin-top: 20px">
        <template #header>
          <div class="card-header">
            <span>优惠规则</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠方式">
              <el-radio-group v-model="form.discountMode">
                <el-radio :label="1">满减</el-radio>
                <el-radio :label="2">优惠券</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠方案">
              <el-radio-group v-model="form.discountProgramme">
                <el-radio :label="1">叠加优惠</el-radio>
                <el-radio :label="2">阶梯优惠</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 满减层级 -->
        <el-row :gutter="20" v-if="form.discountMode === 1">
          <el-col :span="24">
            <el-table :data="form.promotionDetail" border>
              <el-table-column label="满金额">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.fullMoney"
                    :min="0"
                    controls-position="right"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="减金额">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.reduceMoney"
                    :min="0"
                    controls-position="right"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button
                    type="danger"
                    link
                    @click="form.promotionDetail.splice(scope.$index, 1)"
                    :disabled="form.promotionDetail.length <= 1"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px">
              <el-button @click="addPromotionDetail">添加层级</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <div class="form-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { activeAdd, activeUpdate, activeGetById } from '@/api/active'

const emit = defineEmits(['refresh'])

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  activityId: undefined as number | undefined,
  activityName: '',
  activityIntroduce: '',
  signTime: [] as string[],
  activityTime: [] as string[],
  signStartTime: '',
  signEndTime: '',
  activityStartTime: '',
  activityEndTime: '',
  ifBond: 0,
  bondMoney: 0,
  activityLabel: '',
  discountMode: 1,
  discountProgramme: 1,
  image: '',
  promotionDetail: [
    {
      fullMoney: 0,
      reduceMoney: 0
    }
  ]
})

// 表单验证规则
const rules = {
  activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
  activityIntroduce: [{ required: true, message: '请输入活动介绍', trigger: 'blur' }],
  signTime: [{ required: true, message: '请选择报名时间', trigger: 'change' }],
  activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }]
}

// 计算属性
const info = computed(() => !!form.activityId)
const unStart = computed(() => form.activityId && !form.activityStartTime)

// 添加优惠详情
const addPromotionDetail = () => {
  form.promotionDetail.push({
    fullMoney: 0,
    reduceMoney: 0
  })
}

// 获取活动详情
const getDetails = async (row: any) => {
  try {
    const res = await activeGetById({ activityId: row.activityId })
    if (res.data.code === '000000') {
      const data = res.data.data
      form.activityId = data.activityId
      form.activityName = data.activityName
      form.activityIntroduce = data.activityIntroduce
      form.signStartTime = data.signStartTime
      form.signEndTime = data.signEndTime
      form.activityStartTime = data.activityStartTime
      form.activityEndTime = data.activityEndTime
      form.signTime = [data.signStartTime, data.signEndTime]
      form.activityTime = [data.activityStartTime, data.activityEndTime]
      form.ifBond = data.ifBond
      form.bondMoney = data.bondMoney
      form.activityLabel = data.activityLabel
      form.discountMode = data.discountMode
      form.discountProgramme = data.discountProgramme
      form.image = data.image
      form.promotionDetail = data.promotionDetail && data.promotionDetail.length > 0 ? data.promotionDetail : [{ fullMoney: 0, reduceMoney: 0 }]
    }
  } catch (error) {
    console.error(error)
  }
}

// 设置详情数据
const setDetails = (row: any) => {
  getDetails(row)
}

// 图片上传成功处理
const handleAvatarSuccess = (response: any, file: any) => {
  // 这里应该调用实际的上传接口，这里只是模拟
  form.image = URL.createObjectURL(file.raw)
}

// 重置表单
const reset = () => {
  form.activityId = undefined
  form.activityName = ''
  form.activityIntroduce = ''
  form.signTime = []
  form.activityTime = []
  form.signStartTime = ''
  form.signEndTime = ''
  form.activityStartTime = ''
  form.activityEndTime = ''
  form.ifBond = 0
  form.bondMoney = 0
  form.activityLabel = ''
  form.discountMode = 1
  form.discountProgramme = 1
  form.image = ''
  form.promotionDetail = [
    {
      fullMoney: 0,
      reduceMoney: 0
    }
  ]
}

// 取消
const cancel = () => {
  reset()
}

// 保存
const save = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      // 处理时间数据
      if (form.signTime && form.signTime.length === 2) {
        form.signStartTime = form.signTime[0]
        form.signEndTime = form.signTime[1]
      }
      if (form.activityTime && form.activityTime.length === 2) {
        form.activityStartTime = form.activityTime[0]
        form.activityEndTime = form.activityTime[1]
      }

      // 构造提交数据
      const submitData = {
        ...form
      }

      try {
        let res
        if (form.activityId) {
          // 编辑
          res = await activeUpdate({ ...submitData, id: form.activityId })
        } else {
          // 新增
          res = await activeAdd(submitData)
        }
        if (res.data.code === '000000') {
          ElMessage.success(form.activityId ? '编辑成功' : '新增成功')
          emit('refresh')
          reset()
        }
      } catch (error) {
        console.error(error)
      }
    }
  })
}

defineExpose({
  setDetails
})
</script>

<style scoped lang="scss">
.add-active-container {
  .form-card {
    .card-header {
      font-weight: bold;
    }
  }
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  .form-footer {
    margin-top: 20px;
    text-align: center;
  }
}
</style>